#coding=utf-8
'''
Created on 2017-04-20

@author: sandy
'''

import logging
import sys
#from twisted.protocols.telnet import Telnet
from twisted.conch.telnet import Telnet
from twisted.internet import reactor, protocol
from pycommon import Const, Utils

import importlib
import zlib

TELNET_USER     =   "admin"
TELNET_PASSWD   =   "111111"


def runCommand(cmdline, client):
    logging.debug(u"cmdline=%s", cmdline)
    strs = cmdline.split(" ")
    cmd = strs[0]
    params = strs[1:]
    
    m = sys.modules['telnetserver']
    func = getattr(m, cmd, None)
    if func:
        try:
            ret = func(client, params)
            if ret:
                if client:
                    client.write(ret+"\r\n")
        except Exception, e:
            logging.exception(u"cmd=%s", cmdline)
            if client:
                client.write("exception %s" % str(e))
    else:
        if client:
            client.write("unkown cmd : %s\r\n" % cmd)  

        
class TelnetClient(Telnet):
    
    def __init__(self, addr):
        self.addr = addr
        
    def toClose(self):
        self.transport.loseConnection()
    
    def welcomeMessage(self):
        return "welcome to censerver command interface\r\n"
    
    def telnet_User(self, user):
        if user!=TELNET_USER:
            self.write("wrong user\r\n")
            self.toClose()
        return "Password"
    
    def telnet_Password(self, passwd):
        if passwd!=TELNET_PASSWD:
            self.write("wrong passwd\r\n")
            self.toClose()
        return "Command"
    
    def telnet_Command(self, cmdline):
        runCommand(cmdline, self)  
        
    def loggedIn(self):
        self.write("type ?<enter> to get help\r\n")       

    def connectionLost(self, reason=protocol.connectionDone):
        logging.debug(u"TelnetClient.connectionLost %s %s",
                      self.addr,
                      reason) 
        
class TelnetServer(protocol.Factory):
    
    def __init__(self):
        pass
    
    def start(self, ip, port):
        logging.debug(u"TelnetServer start")
        reactor.listenTCP(port, self, interface=ip)
    
    def stop(self):
        pass
    
    def buildProtocol(self, addr):
        logging.debug(u"new telnet client from %s", str(addr))
        return TelnetClient(addr)
    
    
instance = TelnetServer()

if __name__ == '__main__':
    pass